package com.situ.student.servlet;

import com.situ.student.common.LoginFilter;
import com.situ.student.model.User;
import com.situ.student.service.UserService;
import com.situ.student.service.impl.UserServiceImpl;
import com.situ.student.util.BeanFactory;
import com.situ.student.util.ServletUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Map;

@WebServlet("/admin/login")
public class LoginServlet extends HttpServlet {
    private final UserService userService = BeanFactory.getBean(UserServiceImpl.class);

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //身份认证
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String captcha = req.getParameter("captcha");//验证码

        //参数有效性验证
        if (!StringUtils.hasText(username)) {
            ServletUtils.renderJson(resp, Map.of("success", false, "error", "用户名不可为空"));
            return;
        }
        if (!StringUtils.hasText(password)) {
            ServletUtils.renderJson(resp, Map.of("success", false, "error", "密码不可为空"));
            return;
        }
        if (!StringUtils.hasText(captcha)) {
            ServletUtils.renderJson(resp, Map.of("success", false, "error", "验证码不可为空"));
            return;
        }

        //获取会话域对象
        HttpSession session = req.getSession();
        String answer = (String) session.getAttribute("captcha");
        if (!captcha.equals(answer)) {
            ServletUtils.renderJson(resp, Map.of("success", false, "error", "验证码不匹配"));
            return;
        }

        //判断此用户在数据库中是否存在
        User dbUser = userService.findByUsername(username);
        if (dbUser == null) {
            ServletUtils.renderJson(resp, Map.of("success", false, "error", "不存在此用户"));
            return;
        }

        //对密码进行加密
        String encrypt = password + "{" + username + "}";
        encrypt = DigestUtils.md5DigestAsHex(encrypt.getBytes());

        // 且密码是否正确
        if (!encrypt.equals(dbUser.getPassword())) {
            ServletUtils.renderJson(resp, Map.of("success", false, "error", "密码不正确"));
            return;
        }

        //标志
        session.setAttribute(LoginFilter.LOGIN_USER_KEY, dbUser);

        ServletUtils.renderJson(resp, Map.of("success", true));

    }
}
